// pages/real/contribute/index.js
const app = getApp()
const utils = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    barHeight: app.globalData.navHeight,
    topTitle:"投稿",
    titleValue:"",
    topNavFlag:0,
    currentVideo:"",
    submitLoadingFlag:false,
    showVideoSpaceList:false,
    topNavList:[
      {
        id:0,
        url:"/static/img/imgs.png",
        name:'实拍图集',
        flag:true
      },
      {
        id:1,
        url:"/static/img/videos.png",
        name:'实拍视频',
        flag:false
      }
    ],
    tagTitle:"请选择您想投稿的房间(单选)",
    tagTitleVideo:"请选择您想投稿的房间(单选)",
    uploadTitle:{
      title:"上传实景图",
      instruct:"(可拖动排序,第一张作为封面图显示)"
    },
    videoSpaceTagList:[],
    videoTagList:[
      {
        id:0,
        flag:false,
        spaceCode:"0",
        spaceName:"单空间"
      },
      {
        id:1,
        flag:false,
        spaceCode:"1",
        spaceName:"全屋"
      },
    ],
    copyTagList:[],
    tagList:[
      ],
    fileList:[],
    uploadList:[],
    initImgUpload:[
      {
        id:66660,

      }
    ],
    initCoverList:[
      {
        id:55555,
        enclosurePath:'/static/img/cover.png'
      }
    ],
    boxHeight:0,//图集上传盒子的高度
    itemHeight:0,//图集上传图片的高度
    customCover:[],
    coverList:[],
    // 图片拖动
    beginIndex:null,
    hidden: true,
    moveflag: false,
    maskImg:"",
    x: 0,
    y: 0,
    elements: [],
    uploadSuccess: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      coverList:this.data.initCoverList
    })
    this.handleGetAllInitList()
  },
  //图片拖拽排序
  //触摸开始
  touchs(e){
    this.setData({
      beginIndex:e.currentTarget.dataset.idx
    })
  },
  //长按图片进入拖动
  _longtap(e){
    var maskImg = e.currentTarget.dataset.img
    this.setData({
      maskImg: maskImg
    })
    const detail = e.currentTarget;
    this.setData({
      x: detail.offsetLeft,
      y: detail.offsetTop,
      beginIndex:detail.dataset.idx
    })
    this.setData({
      hidden: false,
      moveflag: true
    })

  },
  //触摸结束
  touchend(e){
    if (!this.data.moveflag) {
      return;
    }
    const x = e.changedTouches[0].pageX
    const y = e.changedTouches[0].pageY
    const list = this.data.elements;
    let data = this.data.fileList;
    for (let j = 0; j < list.length; j++) {
      const item = list[j];
      if (x > item.left && x < item.right && y > item.top && y < item.bottom) {
        console.log('进来了')
        const endIndex = item.dataset.idx;
        const beginIndex = this.data.beginIndex;
        //向后移动
        if (beginIndex < endIndex) {
          let tem = data[beginIndex];
          for (let i = beginIndex; i < endIndex; i++) {
            data[i] = data[i + 1]
          }
          data[endIndex] = tem;
        }
        //向前移动
        if (beginIndex > endIndex) {
          let tem = data[beginIndex];
          for (let i = beginIndex; i > endIndex; i--) {
            data[i] = data[i - 1]
          }
          data[endIndex] = tem;
        }
 
        this.setData({
          maskImg:data[endIndex].enclosurePath,
          fileList: data
        })
      }
    }
    this.setData({
      hidden: true,
      moveflag: false
    })
  },
  //滑动
  touchm(e){
    // console.log(e)
    if (this.data.moveflag) {
      const x = e.touches[0].pageX
      const y = e.touches[0].pageY
      console.log(this.data.boxHeight)
        this.setData({
          x: x - 75,
          // y: y - this.data.boxHeight-this.data.itemHeight-400
          y: y-this.data.boxHeight-50
        })
    }
  },
  onChange(e){
    this.setData({
      titleValue:e.detail
    })
  },
  handleChangeVideoType(){
    this.setData({
      showVideoSpaceList:true
    })
  },
  handleChangeVideoTypeClose(){
    this.setData({
      showVideoSpaceList:false
    })
    this.handleClearVideoSpaceTagList()
  },
  handleClearVideoSpaceTagList(){
    this.setData({
      videoSpaceTagList:this.data.videoSpaceTagList.map(item=>{
        item.flag=false
        return item
      })
    })
  },
  removePic(e){
    const index=e.currentTarget.dataset.idx
    const {fileList} =this.data
    fileList.splice(index,1)
    this.setData({
      fileList:fileList
    })
  },
  deleteImg(e){
    const index=e.detail.index
    const {fileList} =this.data
    fileList.splice(index,1)
    this.setData({
      fileList:fileList
    })
  },
  addFilelistImg(){
    console.log('来了老弟')
    const that=this
    const {fileList} =that.data
    const len=fileList.length 
    wx.chooseImage({
      count:9-len,
      // mediaType:['image'],
      sourceType:['album', 'camera'],
      success(res) {
        utils.globalShowTip(true)
        console.log(res)
        const files=res.tempFiles
        // let uploadLists=[]
        files.forEach(item=>{
          wx.uploadFile({
            url: app.globalData.api.getRealAttachmentUpload, // 仅为示例，非真实的接口地址
            filePath: item.path,
            name: 'file',
            formData: { file: item },
            success(res) {
              const data= JSON.parse(res.data)
              const str={
                ...item,...data.data
              }
              // uploadLists.push(str)
              fileList.push(str)
              that.setData({
                fileList:fileList
              },()=>{
                //获取到图片url的数组后，回调里执行下面的原因是：为了拖拽初始化
                  var query = wx.createSelectorQuery();
                  var nodesRef = query.selectAll(".imgItem");
                  nodesRef.fields({
                    dataset: true,
                    rect: true
                  }, (result) => {
                    that.setData({
                      elements: result
                    })
                  }).exec()
                })
              console.log(that.data.fileList)
              var query = wx.createSelectorQuery()
              query.select('.upload-img-new').boundingClientRect((rect)=>{
                console.log(rect)
                that.setData({
                 boxHeight:rect.top
                //  boxTop:rect.
                })
              }).exec();
              query.select('.imgItem').boundingClientRect((rect)=>{
                that.setData({
                 itemHeight:rect.height
                })
              }).exec();
              utils.globalShowTip(false)
            }
          })
        })
      },
      fail(err){
        console.log(err)
      }
    })
  },
  uploadVideoMdeio(){
    const that=this
    wx.chooseMedia({
      count:1,
      mediaType:['video'],
      sourceType:['album', 'camera'],
      success(res) {
        utils.globalShowTip(true)
        console.log(res)
        const file=res.tempFiles[0]
        if(file.size>200*1024*1024){
          wx.showToast({ icon: 'warning', title: '文件超出上传大小限制(200M)!', duration: 2000 })
          return
        }
        wx.uploadFile({
          url: app.globalData.api.getRealAttachmentUpload, // 仅为示例，非真实的接口地址
          filePath: file.tempFilePath,
          name: 'file',
          formData: { file: file },
          success(res) {
         const data= JSON.parse(res.data)
            //上传完成需要更新 fileList thumbTempFilePath 测试上传视频
            const { fileList = [] ,topNavFlag,coverList} = that.data;
            console.log(data)
            let strFile={}
            if(topNavFlag===1){
              strFile={
                // thumb:file.thumbTempFilePath,
                path:file.thumbTempFilePath,
              }
            }
            fileList.push({ ...file, ...data.data, ...strFile });
            that.setData({ 
              uploadList:JSON.parse(JSON.stringify(fileList)),
              fileList ,
              currentVideo:data.data.enclosurePath
            });
            console.log(fileList)
            that.handlePubGetCover(data.data.enclosurePath)
            utils.globalShowTip(false)
          },
        });
      }
    })
  },
  handleAfterUpload(event){
    const {file}=event.detail 
    console.log(event)
    // if
    const that=this
    wx.uploadFile({
      url: app.globalData.api.getRealAttachmentUpload, // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'file',
      formData: { file: file },
      success(res) {
     const data= JSON.parse(res.data)
        //上传完成需要更新 fileList thumbTempFilePath 测试上传视频
        const { fileList = [] ,topNavFlag,coverList} = that.data;
        console.log(data)
        fileList.push({ ...file, ...data.data });
        that.setData({ 
          uploadList:JSON.parse(JSON.stringify(fileList)),
          fileList ,
          currentVideo:data.data.enclosurePath
        });
        console.log(that.data.fileList)
      },
    });
  },
  handlePubGetCover(list){
    // this.setData({
    //   coverList:this.data.initCoverList
    // })
    const {coverList , initCoverList ,customCover} =this.data
    utils.$http(app.globalData.api.getRealVedioCover, list, 'POST', true, 'JSON').then(res => {
      if(res.success){
        wx.showToast({ icon: 'success', title: '系统已自动挑选出三张封面图', duration: 1500 })
        const canCont=coverList.some(item=>item.id===55555)
        if(canCont){
          const newArr=res.data.map(item=>{
              item.flag=false
              return item
            }).concat(initCoverList)
            this.setData({
            coverList:newArr
            })
        }else{
          const newArr=res.data.map(item=>{
            item.flag=false
            return item
          }).concat(customCover)
          this.setData({
          coverList:newArr
          })
        }
      }
     })
  },
  //重新获取封面图
  obtainGetCoverImg(){
    if(this.data.fileList.length===0){
      wx.showToast({ icon: 'warning', title: '请先上传视频', duration: 1000 })
      return
    }
    this.handlePubGetCover(this.data.currentVideo)
  },
  handleSubmit(){
    const userInfo=wx.getStorageSync('userInfo')
    const unionid=wx.getStorageSync("unionid")
    const phone = wx.getStorageSync('phone')
    if(!unionid || !phone){
      wx.showToast({ icon: 'warning', title: '请完善登录信息', duration: 1000 })
      return
    }
    const users={
      createBy:unionid
    }
    const {titleValue,topNavFlag ,videoSpaceTagList,tagList,fileList
      ,coverList
    } =this.data
    const  arr=tagList.filter(item=>item.flag)
    const  spaceList=videoSpaceTagList.filter(item=>item.flag) || []
    console.log(spaceList)
    // return
    console.log(videoSpaceTagList)
    const imgs=fileList.map((item,index)=>{
      const strs={
        picUrl:item.enclosurePath,
        name:item.originalFileName,
        sort:index
      }
      return strs
    })
    const selects=coverList.some(item=>item.flag)
    const cosvers=selects?coverList.filter(item=>item.flag):[]
    let toastList=[]
    const toast1=[
      {
        name:'空间',
        flag:arr.length===0
      },{
        name:'标题',
        flag:titleValue===''
      },
      {
        name:'实景图',
        flag:imgs.length===0
      }
    ]
    const toast2=[
      {
        name:'封面图',
        flag:cosvers.length===0
      }
    ] 
    const toast3=[
      {
        name:'空间',
        flag:spaceList.length===0
      }
    ] 
    if(topNavFlag===0){
      toastList=toast1
      for(let i=0;i<toastList.length;i++){
        if(toastList[i].flag){
          wx.showToast({ icon: 'error', title: `请完善${toastList[i].name}`, duration: 1000 })
          return
        }
      }
    }else{
      if(arr.length===0){
        wx.showToast({ icon: 'error', title: `请完善视频类型`, duration: 1000 })
            return
      }
      if(arr[0].spaceCode==='1'){
        toastList=toast1.concat(toast2)
        for(let i=0;i<toastList.length;i++){
          if(toastList[i].flag){
            wx.showToast({ icon: 'error', title: `请完善${toastList[i].name}`, duration: 1000 })
            return
          }
        }
      }else{
        toastList=toast3.concat(toast1).concat(toast2)
        for(let i=0;i<toastList.length;i++){
          if(toastList[i].flag){
            wx.showToast({ icon: 'error', title: `请完善${toastList[i].name}`, duration: 1000 })
            return
          }
        }
    }
    }
    this.setData({
      submitLoadingFlag:true
    })
    const str={
      designerPic:userInfo.headImg,
      contributeType:topNavFlag,
      source:0,
      spaceCode:topNavFlag===0?arr[0].spaceCode:spaceList.length?spaceList[0].spaceCode:null,
      spaceName:topNavFlag===0?arr[0].spaceName:spaceList.length?spaceList[0].spaceName:null,
      realityName:titleValue,
      realityPic:topNavFlag===0?imgs[0].picUrl:cosvers[0].enclosurePath ,
      realityImageList:topNavFlag===0?imgs:null,
      videoName:topNavFlag===1?imgs[0].name:null ,
      videoType:topNavFlag===1?arr[0].spaceCode:null ,
      videoUrl:topNavFlag===1?imgs[0].picUrl:null ,
      ...users
    }
    utils.$http(app.globalData.api.getRealContribImgsOrVideo, str, 'POST', true, 'JSON').then(res => {
      if(res.success){
        // wx.navigateBack({
        //   success: function() {  
        //     currentPage.handleInitSearch(); // 执行前一个页面的默认刷新方法  
        // } 
        // })
        setTimeout(()=>{
          this.setData({
            submitLoadingFlag:false
          })
        },500)
        wx.navigateTo({
          url: '/pages/real/contresult/index',
        })
      }
    })
    
  },
  handleGoBack(){
    wx.navigateBack({
      
    })
  },
  handleGetAllInitList(){
    utils.$http(app.globalData.api.GetFeaturedAllOnespace, {}, 'Get', true, 'JSON').then(res => {
     if(res.success){
       const list=res.data.map(item=>{
           item.flag=false
           return item
         })
       this.setData({
         tagList:list,
         copyTagList:JSON.parse(JSON.stringify(list)),
         videoSpaceTagList:JSON.parse(JSON.stringify(list)),
       })
       
     }
    })
  },
  goResult(){
    wx.navigateTo({
      url: '/pages/real/contresult/index',
    })
  },
  //删除自定义封面图
  handleDeleteCusCover(e){
    const list=e.currentTarget.dataset.list
    const {coverList , initCoverList} =this.data
    this.setData({
      coverList:coverList.filter(item=>!item.customId).concat(initCoverList)
    })

  },
  //自定义封面图
  handleCoverClick(item){
    const list=item.currentTarget.dataset.list
    const that=this
    if(list.id===55555){
      if(this.data.fileList.length===0){
        wx.showToast({ icon: 'warning', title: '请先上传视频', duration: 1000 })
        return
      }
      wx.chooseMedia({
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        camera: 'back',
        success(res) {
          utils.globalShowTip(true)
          const file=res.tempFiles[0]  
          wx.uploadFile({
            url: app.globalData.api.getRealAttachmentUpload, // 仅为示例，非真实的接口地址
            filePath: file.tempFilePath,
            name: 'file',
            formData: { file: file },
            success(res) {
           const data= JSON.parse(res.data)
           data.data.flag=false
           data.data.customId=9998588666
           const str=data.data
           const {  coverList} = that.data;
           coverList.pop()
           coverList.push(str)
           const arr=[]
           arr.push(str)
           that.setData({
            coverList,
            customCover:arr
           })
           console.log(that.data.coverList)
          utils.globalShowTip(false)
          // fileList.push({ ...file, urls:data.data.enclosurePath,...strFile });
          }
        })
        }
      })
    }else{
      const { coverList = [] } = this.data
      coverList.forEach(c=>{
          if(list.id===c.id){
            c.flag=true
          }else{
            c.flag=false
          }
      })
      this.setData({coverList})
    }
   
  },
  handleMarkClick(item){
    const list=item.currentTarget.dataset.list
    const datas=this.data.videoSpaceTagList.map(l=>{
      if(l.id===list.id){
        l.flag=true
      }else{
        l.flag=false
      }
      return l
    })
      this.setData({
        videoSpaceTagList:datas
    })
    
  },
  handleInitContriData(){
    this.setData({
      showVideoSpaceList:false,
      fileList:[],
      titleValue:"",
      coverList:this.data.initCoverList,
      tagList:this.data.topNavFlag===0?this.data.copyTagList:this.data.videoTagList
    })
    this.handleClearVideoSpaceTagList()
  },
  handleTabClick(item){
    const list=item.currentTarget.dataset.list
    this.setData({
       topNavFlag:list.id,
       showVideoSpaceList:false,
       titleValue:"",
       fileList:[],
       coverList:this.data.initCoverList
    })
    this.handleClearVideoSpaceTagList()
    if(list.id===0){
      this.setData({
        tagTitle:"请选择您想投稿的房间(单选)",
        tagList:this.data.copyTagList,
        uploadTitle:{
          title:"上传实景图",
          instruct:"(可拖动排序,第一张作为封面图显示)"
        },
      })
    }else{
      this.setData({
        tagTitle:"请选择投稿的视频类型(单选)",
        tagList:this.data.videoTagList,
        uploadTitle:{
          title:"上传实景",
          instruct:"(最多可上传1个实拍视频)"
        },
      })
    }
    this.setData({
      topNavList:this.data.topNavList.map(t=>{
      if(t.id===list.id){
        t.flag=true
      }else{
        t.flag=false
      }
      return t
    })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})